package com.unisound.tracelog.client.sql.mybatis;

import com.unisound.tracelog.client.core.context.SpanContextManager;
import com.unisound.tracelog.client.core.enums.TypeEnum;
import com.unisound.tracelog.client.core.model.RootStartSpan;
import com.unisound.tracelog.client.core.properties.TraceLogClientProperties;
import com.unisound.tracelog.client.core.service.TraceLogService;
import com.unisound.tracelog.client.core.support.parameter.ParameterValue;
import com.unisound.tracelog.common.model.span.EndSpan;
import com.unisound.tracelog.common.model.span.StartSpanResult;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.regex.Matcher;


@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "queryCursor", args = {MappedStatement.class, Object.class, RowBounds.class})
})
public class ExecutorSqlInterceptor implements Interceptor {
    private static final Logger LOGGER = Logger.getLogger("com.unisound.tracelog.client.sql.mybatis.ExecutorSqlInterceptor");
    private final TraceLogClientProperties traceLogClientProperties;
    private final TraceLogService traceLogService;

    public ExecutorSqlInterceptor(TraceLogClientProperties traceLogClientProperties, TraceLogService traceLogService) {
        this.traceLogClientProperties = traceLogClientProperties;
        this.traceLogService = traceLogService;
    }

    /**
     * DATE_FORMAT
     */
    private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        if (!traceLogClientProperties.getSql().isEnabled()) return invocation.proceed();
        if (SpanContextManager.isRoot()) return invocation.proceed();

        // 记录慢SQL
        StartSpanResult startSpanResult = startWithoutException(invocation);

        Map<String, String> errorMessageMap = null;

        try {
            return invocation.proceed();
        } catch (Throwable e) {
            errorMessageMap = new HashMap<>();
            errorMessageMap.put("error", e.getMessage());
            throw e;
        } finally {
            endWithoutException(null, startSpanResult, errorMessageMap);
        }
    }

    private StartSpanResult startWithoutException(Invocation invocation) {
        try {
            // 任务名称
            String name = invocation.getMethod().getName();

            // 服务名称
            String serverName = traceLogClientProperties.getDefaultServerName();

            // 任务参数
            Map<String, ParameterValue> parameterMap = parameterMap(invocation);

            return traceLogService.start(new RootStartSpan(name, serverName, TypeEnum.SQL.getType(), null, parameterMap));
        } catch (Throwable e) {
            LOGGER.warning("TraceLog startWithoutException error. cause=" + e.getMessage());
            return null;
        }
    }

    private Map<String, ParameterValue> parameterMap(Invocation invocation) {
        Object[] args = invocation.getArgs();
        MappedStatement mappedStatement = (MappedStatement) args[0];
        Object parameter = getParameter(args);

        String statementId = mappedStatement.getId();
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        Configuration configuration = mappedStatement.getConfiguration();
        String sql = getSql(boundSql, parameter, configuration);

        Map<String, ParameterValue> parameterMap = new HashMap<>();
        parameterMap.put("statementId", new ParameterValue(statementId, true));
        parameterMap.put("sql", new ParameterValue(sql, true));
        return parameterMap;
    }

    private void endWithoutException(Object result, StartSpanResult startSpanResult, Map<String, String> errorMessageMap) {
        try {
            traceLogService.end(new EndSpan(startSpanResult, errorMessageMap == null ? result : errorMessageMap));
        } catch (Throwable e) {
            LOGGER.warning("TraceLog endWithoutException error. cause=" + e.getMessage());
        }
    }


    private Object getParameter(Object[] args) {
        return args.length > 1 ? args[1] : null;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    private String getSql(BoundSql boundSql, Object parameterObject, Configuration configuration) {
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
        if (parameterMappings != null) {
            for (int i = 0; i < parameterMappings.size(); i++) {
                ParameterMapping parameterMapping = parameterMappings.get(i);
                if (parameterMapping.getMode() != ParameterMode.OUT) {
                    Object value;
                    String propertyName = parameterMapping.getProperty();
                    if (boundSql.hasAdditionalParameter(propertyName)) {
                        value = boundSql.getAdditionalParameter(propertyName);
                    } else if (parameterObject == null) {
                        value = null;
                    } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                        value = parameterObject;
                    } else {
                        MetaObject metaObject = configuration.newMetaObject(parameterObject);
                        value = metaObject.getValue(propertyName);
                    }
                    sql = replacePlaceholder(sql, value);
                }
            }
        }
        return sql;
    }

    private String replacePlaceholder(String sql, Object propertyValue) {
        String result;
        if (propertyValue != null) {
            if (propertyValue instanceof String) {
                result = "'" + propertyValue + "'";
            } else if (propertyValue instanceof Date) {
                result = "'" + DATE_FORMAT.format(propertyValue) + "'";
            } else {
                result = propertyValue.toString();
            }
        } else {
            result = "null";
        }
        return sql.replaceFirst("\\?", Matcher.quoteReplacement(result));
    }

}
